<?php
namespace wechat;


use think\facade\Db;

/**
 * @package 微信授权控制器
 */
class WechatOfficial{
    //微信授权配置信息
    private $wechat_config;

    public function __construct() {
        $config = Db::name('config_data')->where('config_id',5)->select();
        $arr = [];
        foreach($config as $v){
            $arr[$v['code']] = $v['value'];
        }
        $this->wechat_config = $arr;
    }


    /**
     * 获取openid
     * @return string|mixed
     */
    public function getUserAccessUserInfo($code = "",$type= 1)
    {
        $access_token = $this->getSingleAccessToken($code,$type);
        return $access_token;
    }


    /**
     * 获取token
     * @return [type] 返回token
     */
    public function getSingleAccessToken($code) {

      $url =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->wechat_config['app_id']."&secret=".$this->wechat_config['secret']."&code=".$code."&grant_type=authorization_code";
//        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->wechat_config['app_id'].'&secret='.$this->wechat_config['secret'].'&js_code='.$code.'&grant_type=authorization_code';

        $access_token = $this->https_request($url);
        return $access_token;
    }




    /**
     * 发送curl请求
     * @param $url string
     * @param return array|mixed
     */
    public function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $AjaxReturn = curl_exec($curl);
        //获取access_token和openid,转换为数组
        $data = json_decode($AjaxReturn,true);
        curl_close($curl);
        return $data;
    }

    /**
     * 解密信息
     * 主要用于wx.getUserInfo时对加密数据的解密。
     *
     * @param $sessionKey
     * @param $iv
     * @param $encryptedData
     * @return array
     * @since 1.3.1
     */
    public function decryptData($sessionKey,$iv,$encryptedData){
        $aesKey = base64_decode($sessionKey);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode( $result,true );
        return $dataObj;
    }
}